package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.dubbo.api.CommentsApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResultVo;
import com.tanhua.server.interceptor.UserHolderThreadLocal;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/3 15:45
 */
@Service
public class CommentsService {

    @DubboReference
    private CommentsApi commentsApi;

    @DubboReference
    private UserInfoApi userInfoApi;


    /**
     * 评论列表查询
     * @param movementId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResultVo comments(String movementId, Integer page, Integer pageSize) {

        // 查询Comment，
        List<Comment> commentList =  commentsApi.findComments(page, pageSize, movementId, CommentType.COMMENT);
        // 判断是否查询到
        if(CollUtil.isEmpty(commentList)){
            return new PageResultVo();
        }

        // 获取userId集合
        List<Long> userIds = CollectionUtil.getFieldValues(commentList, "userId", Long.class);
        // 根据userId查询用户信息。
        Map<Long, UserInfo> map = userInfoApi.findByIds(null, userIds);

        List<CommentVo> list = new ArrayList<>();
        for (Comment comment : commentList) {

            UserInfo userInfo = map.get(comment.getUserId());
            if(userInfo != null){
                // 封装数据
                CommentVo commentVo = CommentVo.init(userInfo, comment);
                // 将封装好得数据添加到集合，再封装到PageResultVo中返回
                list.add(commentVo);
            }
        }

        // 封装PageResult返回
        PageResultVo resultVo = new PageResultVo();
        resultVo.setItems(list);
        return resultVo;

    }

    // 发布评论
    public void saveComments(String movementId, String comment) {

        Comment comment1 = new Comment();
        Long userId = UserHolderThreadLocal.getId();

        comment1.setPublishId(new ObjectId(movementId));
        comment1.setUserId(userId);
        comment1.setContent(comment);
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setCreated(System.currentTimeMillis());
        // 保存
        commentsApi.saveComments(comment1);

    }
}
